package fr.vahren.processing.picking;

import processing.core.PApplet;
import processing.core.PConstants;
import processing.core.PGraphics;

public class Picker {

	public static final int BACKGROUND = 100;
	private PApplet parent;
	private PGraphics buffer;

	public Picker(PApplet main) {
		this.parent = main;
		buffer = parent.createGraphics(parent.width, parent.height,
				PConstants.P3D);
	}

	public void init() {
		buffer.beginDraw();
		buffer.setMatrix(parent.g.getMatrix());
		buffer.background(BACKGROUND);
		buffer.noStroke();
	}

	public void start(int color) {
		if (color != BACKGROUND) {
			buffer.fill(color - 16777215);
		} else {
			System.err.println("WRONG COLOR NO BLACK PLZ");
		}
	}

	public void stop() {
		buffer.endDraw();
	}

	public int pick(int x, int y) {
		if (x >= 0 && x < parent.width && y >= 0 && y < parent.height) {
			buffer.loadPixels();
			int pixel = buffer.pixels[x * parent.width + y] + 16777215;

			return pixel;

		}
		return BACKGROUND;
	}

	/**
	 * @return the buffer
	 */
	public PGraphics getBuffer() {
		return buffer;
	}

	/**
	 * @param buffer
	 *            the buffer to set
	 */
	public void setBuffer(PGraphics buffer) {
		this.buffer = buffer;
	}

}
